package cn.db.service;

import cn.db.feign.UserInfoFeign;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

@Service
public class UserService {

    @Autowired
    private UserInfoFeign userInfoFeign;


    /**
     * 单线程串行方法
     * @param userId
     * @return
     */
    public Object getUserInfo(long userId){
        long currentTime = System.currentTimeMillis();
        //获取用户信息接口
        String userString = userInfoFeign.getUserInfo(userId);
        JSONObject userinfo = JSONObject.parseObject(userString);

        String userMoneyString = userInfoFeign.getUserMoney(userId);
        JSONObject userMoney = JSONObject.parseObject(userMoneyString);

        JSONObject result = new JSONObject();
        result.putAll(userinfo );
        result.putAll(userMoney);
        System.out.println("耗时："+(System.currentTimeMillis()-currentTime));
        return result;
    }

    /**
     * 多线程并发的方式调用，需要下一个调用不依赖上一个接口的返回值无状态化，且会造成阻塞问题（响应时间是以最长的线程为最终阻塞时间）
     * @param userId
     * @return
     */
    public Object  getUserInfoByThread(long userId){
        long currentTime = System.currentTimeMillis();

        Callable userCall = new Callable() {
            @Override
            public JSONObject call() throws Exception {
                //获取用户信息接口
                String userString = userInfoFeign.getUserInfo(userId);
                JSONObject userinfo = JSONObject.parseObject(userString);
                return userinfo;
            }
        };
        FutureTask<JSONObject> userTask = new FutureTask<>(userCall);
        Thread userInfoThread = new Thread(userTask);
        userInfoThread.start();

        Callable moneyCall = new Callable() {
            @Override
            public JSONObject call() throws Exception {
                //获取用户信息接口
                String userMoneyString = userInfoFeign.getUserMoney(userId);
                JSONObject money = JSONObject.parseObject(userMoneyString);
                return money;
            }
        };
        FutureTask<JSONObject> moneyTask = new FutureTask<>(moneyCall);
        Thread moneyThread = new Thread(moneyTask);
        moneyThread.start();

        JSONObject result = new JSONObject();
        try {
            result.putAll(userTask.get() );
            result.putAll(moneyTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("耗时："+(System.currentTimeMillis()-currentTime));
        return result;
    }


}
